package com.weilele.mvvm.utils.net.gson_adapter;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.TypeAdapter;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.orhanobut.logger.Logger;
import com.weilele.mvvm.MvvmConf;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import kotlin.jvm.functions.Function2;
import kotlin.jvm.functions.Function3;
import okhttp3.ResponseBody;
import retrofit2.Converter;

final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;
    private final Function3<T, Throwable, Object, Object> resultCall;

    public GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter, Function3<T, Throwable, Object, Object> resultCall) {
        this.gson = gson;
        this.adapter = adapter;
        this.resultCall = resultCall;
    }

    public GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this(gson, adapter, null);
    }

    @Override
    public T convert(ResponseBody value) throws IOException {

        try {
            T result;
//            if (MvvmConf.INSTANCE.getIS_DEBUG()) {
//                BufferedReader bufferedReader = new BufferedReader(value.charStream());
//                StringBuilder sb = new StringBuilder();
//                String temp = null;
//                while ((temp = bufferedReader.readLine()) != null) {
//                    sb.append(temp);
//                }
//                bufferedReader.close();
//                String json = sb.toString();
//                Logger.v("-------------------------okHttp 返回数据  start---------------------------");
//                Logger.json(json);
//                Logger.v("-------------------------okHttp 返回数据  end---------------------------");
//                result = adapter.fromJson(json);
//            } else {
            JsonReader jsonReader = gson.newJsonReader(value.charStream());
            result = adapter.read(jsonReader);
            if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
                throw new JsonIOException("JSON document was not fully consumed.");
            }
//            }
            if (resultCall != null) {
                try {
                    resultCall.invoke(result, null, result);
                } catch (Throwable t) {
                    t.printStackTrace();
                    resultCall.invoke(null, t, result);
                }
            }
            return result;
        } finally {
            value.close();
        }
    }
}
